package com.example.jdbctemplate.dao;

import com.example.jdbctemplate.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;

import javax.sql.DataSource;
import java.util.List;

/**
 * @author fanhang
 */
public interface UserDao {
    int insert(User user);

    User findById(long id);

    List<User> findByAge(int age);

    /**
     * 模糊查询
     */
    List<User> findGreaterAgeLikeName(int age, String name);


    class UserDaoImpl extends NamedParameterJdbcDaoSupport implements UserDao {
        private final RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);

        public UserDaoImpl(DataSource dataSource) {
            super.setDataSource(dataSource);
        }

        @Override
        public int insert(User user) {
            String sql = " insert into t_user (id, name, age, remark) values ( :id, :name, :age, :remark ) ";
            return getNamedParameterJdbcTemplate().update(sql, new BeanPropertySqlParameterSource(user));
        }

        @Override
        public User findById(long id) {
            String sql = " select * from t_user where id = ? ";
            return getJdbcTemplate().queryForObject(sql, User.class, id);
        }

        @Override
        public List<User> findByAge(int age) {
            String sql = " select * from t_user where age = ? ";
            return getJdbcTemplate().query(sql, rowMapper, age);
        }

        @Override
        public List<User> findGreaterAgeLikeName(int age, String name) {
            String sql = " select * from t_user where age > ? and name like CONCAT('%', ?, '%') ";
            return getJdbcTemplate().query(sql, rowMapper, age, name);
        }
    }
}
